package com.supinfo.youfood.forms;

import java.rmi.RemoteException;

import javax.xml.rpc.ServiceException;

import org.apache.log4j.Logger;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.IModel;

import com.supinfo.food.entities.User;
import com.supinfo.food.services.UserService;
import com.supinfo.food.services.UserServiceService;
import com.supinfo.food.services.UserServiceServiceLocator;
import com.supinfo.youfood.pages.user.add.UserAdd;
import com.supinfo.youfood.session.Session;

/**
 * Formulaire de connexion
 * @author Keitaro
 */
@SuppressWarnings("rawtypes")
public class ConnexionForm extends Form {
	
	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(getClass());

	@SuppressWarnings("unchecked")
	public ConnexionForm(String id, IModel model) {
		super(id, model);
		
		TextField login = new TextField("login");
		login.setRequired(true);
		add(login);
		
		add(new PasswordTextField("password"));
	}
	
	@Override
	protected void	onSubmit() {
		User user = (User) getModelObject();
		User reponse = null;
		
		logger.info("Appel du webservice de connexion [" + user.getLogin() + "]");
		try {
			UserServiceService binding = new UserServiceServiceLocator();
			UserService service = binding.getUserService();
			reponse = service.connexion(user.getLogin(), user.getPassword());
		} catch (ServiceException e) {
			logger.info("Service can not be reached.");
		} catch (RemoteException e) {
			logger.info("Service does not responded.");
		}
		
		if (reponse != null) {
			Session session = (Session) getSession();
			session.setUser(reponse);
			logger.info("Connexion success");
			setResponsePage(new UserAdd());
		} else {
			logger.info("Connexion failed");
			info("Connexion failed");
		}
		
		
	}

}
